<?php
/**
 * Created by PhpStorm.
 * User: gxh
 * Date: 16-12-30
 * Time: 上午9:41
 */
namespace Inbound\Controller;

use \Home\Controller\CommonController;
use \Warehouse\Controller\StockInController;
use \Inbound\Service\InboundshipmentplanService;
use \Inbound\Service\PackageboxService;
use \Inbound\Service\BarcodeService;
use \Inbound\Service\PublicInfoService;
use \Api\Service\Amazon\InboundService;
use Inbound\Service\PrepareneedsService;
use Inbound\Service\PublicPlugService;
use Think\Exception;

class InboundshipmentplanController extends CommonController
{

    //库存服务层对象
    public $Inboundshipmentplan = NULL;
    public $API_Inbound         = NULL;
    public $packagebox          = NULL;
    public $barcode             = NULL;
    public $accounts            = NULL;
    public $Prepareneeds        = NULL;
    public $saleStatus          = NULL;


    //条件
    public $condition = array();

    //标志符
    public $flag;

    /**
     * 默认构造方法
     */
    public function __construct()
    {
        $this->Inboundshipmentplan = D('Inboundshipmentplan','Service');
        $this->packagebox          = D('Packagebox','Service');
        $this->barcode             = D('Barcode','Service');
        $this->accounts            = PublicInfoService::get_accounts();
        $this->saleStatus          = PublicInfoService::getSaleStatus();
        $this->API_Inbound         = D('Api/Amazon/Inbound','Service');
        $this->Prepareneeds        = D('Prepareneeds','Service');
        parent::__construct();
    }
    public function addskuinfo(){
        C("LAYOUT_ON",FALSE);
        //$this->assign('attr',$_GET);
        $content = $this->fetch('Inboundshipmentplan/addskuinfo');

        echo $content;
    }

    /**
     * 平台计划单首页显示
     */
    public function index()
    {
        $this->condition = $_GET;
        $failure = 0;
        if ($_GET){
            if($_GET['shipmentid']){
                $where = array('shipmentid'=>$_GET['shipmentid'],'seller_mark_shiped_status'=>10);
                $here = M('fba_shipment_shiped_failure',' ','fbawarehouse')->where($where)->find();
                if($here){
                    $failure = 1;
                }
            }
            $data            = $this->Inboundshipmentplan->select($_GET,TRUE);
        }else{
            $data = array();
        }
        $this->assign('transport_way',PublicInfoService::get_transport_way_array());
        $this->assign('inbound_status',PublicInfoService::get_inbound_status());
        $this->assign('site',PublicInfoService::get_site_array());
        $this->assign('seller',publicInfoService::salesmanGet());
        $this->assign('accounts',$this->accounts);
        $this->assign('page',$this->Inboundshipmentplan->page);
        $this->assign('count',$this->Inboundshipmentplan->count);
        $this->assign('data',$data);
        $this->assign('failure',$failure);
        $this->display();
    }


    /**
     * 下载
     */
    public function download()
    {
        $download_model = $this->Inboundshipmentplan->Inboundshipmentplandetail;
        $fileName = '平台计划单报表.csv';
        $title = $this->inbound_title();
        $data = $download_model->get_this_model($_GET)->select();
        $this->Inboundshipmentplan->action_down($fileName,$title,$data);
    }
    /**
     * @return array
     * 平台计划单下载表头
     */
    function inbound_title(){
        return $titile = array(
            "账号名",
            "状态",
            "shipmentId",
            "所属备货需求批次号",
            "站点",
            "最佳到货时间",
            "承运商服务",
            "起运地",
            "目的地",
            "亚马逊配送中心标识",
            "计划单生成人",
            "计划单生成时间",
        );
    }
    /**
     * 下载
     */
    public function downloadother()
    {
//        print_r($_GET);
//        exit;
        $download_model = $this->Inboundshipmentplan->Inboundshipmentplandetail;
        $fileName = 'FBA平台计划单.csv';
        $title = $this->inbound_title_other();
//        $data = $download_model->get_this_model($_GET)->select();//搜索条件后的数组
        $data=$download_model->get_plan_detail($_GET)->select();
//        print_r($data);
//        exit;
        $this->Inboundshipmentplan->action_down_other($fileName,$title,$data);
    }
    /**
     * @return array
     * 平台计划单下载表头
     */
    function inbound_title_other(){
        return $titile = array(
            "shipmentId",
            "计划单生成时间",
            "账号名称",
            "站点",
            "起运地",
            "目的地",
            "亚马逊配送中心标识",
            "sellerSKU",
            "SKU",
            "采购订单号",
            "采购员",
            "采购名称",
            "报关品名",
            "英文品名",
            "海关编码",
            "退税率",
            "品牌",
            "型号",
            "申报要素",
            "净重KG(单个SKU)",
            "毛重KG（GW/PCS,包装后的单个SKU）",
            "体积CM3（包装后的单个SKU体积）",
            "需求数量",
            "含税采购单价",
            "含税采购总额",
            "是否出口退税",
            "采购主体",
            "要求到货时间",
            "销售员",
            "是否单独发货",
            "状态",
            "物流渠道",
            "创建人",
            "创建时间",
            "销售确认人",
            "销售确认时间",
            "物流预审人",
            "物流预审时间",
            "备注",
            "货物等级",
            "海外监管条件",
        );
    }

    /*
    * 上传发票信息
    */
    public function upload_invoice()
    {
        if($_POST['id']&&$_POST['id']!=''){
            $id     = trim($_POST['id']);
            $this->condition = array('id'=>$id);
            $status = $this->Inboundshipmentplan->Inboundshipmentplandetail->get_field_by_param($this->condition,array('status'));
            if($status[0]['status']<20 || $status[0]['status']==100){
                echo '<script>alert("状态不符合");window.location.href="index"</script>';
                exit;
            }
            if($_FILES['invoice_path']['size']>0){
                $config = array(
                    'rootPath'   =>    './',
                    'savePath'   =>    '/Public/uploads/',
                    'maxSize'  => 3145728,// 设置附件上传大小
                    'exts'     => array(
                        'xls',
                        'xlsx'
                    ),// 设置附件上传类型
                    'saveRule' =>array('time',''),
                );
                $upload = new \Think\Upload($config);// 实例化上传类
                // 上传单个文件
                $info = $upload->upload();
                if(!$info){// 上传错误提示错误信息
                    $this->error($upload->getError());
                }else{// 上传成功 获取上传文件信息
                    $data['invoice_path'] = $info['invoice_path']['savepath'].$info['invoice_path']['savename'];
                    $this->condition      = array(
                        'id'=>$id
                    );
                    $res = $this->Inboundshipmentplan->update($this->condition,$data);
                    if($res){
                        echo '<script>alert("上传成功");window.location.href="index"</script>';
                        exit;
                    }
                }
            }else{
                $this->error('上传文件不能为空！');
            }
        }
    }

    //下载发票信息
    public function download_invoice(){
        $id = I('get.id');
        $shipmentid = I('get.shipmentid');
        $seller_name = I('get.seller_name');
        $site_id = I('get.site_id');
        $result = $this->Inboundshipmentplan->getPlanDetailForId($id);
        if(!$result){
            echo "<script>alert('下载错误，请重新尝试或联系it')</script>";die;
        }
        vendor('PHPExcel.PHPExcel');

        /*模板存放目录*/

        $templateFile = realpath(__ROOT__) . '/Admin/Inbound/Template/' . date('Y-m-d',time());
        //$templateFile = '/var/www/fbawarehouse'. '/Admin/Inbound/Template/' . $templateFileName;

        $PHPExcel = new \PHPExcel();
        //$PHPReader = new \PHPExcel_Reader_Excel2007();

        $currentSheet = $PHPExcel->getSheet(0);
        $PHPExcel->getDefaultStyle()->getFont()->setSize(12);
        $PHPExcel->getDefaultStyle()->getAlignment()->setWrapText(true);
        $PHPExcel->getDefaultStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
        $PHPExcel->getDefaultStyle()->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_TOP);
        $PHPExcel->getDefaultStyle()->getFont()->getColor()->setARGB(\PHPExcel_Style_Color::COLOR_DARKBLUE);
        $currentSheet->getStyle('A1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $currentSheet->getStyle('A2')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $currentSheet->getColumnDimension('A')->setWidth(15);
        $currentSheet->getColumnDimension('B')->setWidth(18);
        $currentSheet->getColumnDimension('C')->setWidth(15);
        $currentSheet->getColumnDimension('D')->setWidth(12);
        $currentSheet->getColumnDimension('E')->setWidth(9);
        $currentSheet->getColumnDimension('F')->setWidth(12);
        $currentSheet->getColumnDimension('D')->setWidth(12);
        $currentSheet->getColumnDimension('G')->setWidth(17);
        $currentSheet->setCellValue('A1', 'COMMERCTAL   INVOICE');
        $currentSheet->setCellValue('A2', '商业发票');
        $currentSheet->setCellValue('A3', 'SHIPPER’S INFORMATION    寄件人资料');
        $currentSheet->setCellValue('A4', 'SHIPPER COMPANY NAME（寄件公司名）：'.$result['shipFromAddress']['name']);
        $currentSheet->setCellValue('A5', 'Addr：'.$result['shipFromAddress']['address']);
        $currentSheet->setCellValue('A6', 'AIRWAY  BILL  NO (运单号)：');
        $currentSheet->setCellValue('A7', 'TOTAL PKGS (总箱数)：'.$result['box'].'PCS ');
        $currentSheet->setCellValue('A8', 'TOTAL WEIGHT(总实重)：'.$result['weight'].'KGS ');
        $currentSheet->setCellValue('A9', 'DELIVERY TERMS ：DDP');
        $currentSheet->setCellValue('A10', 'CONSIGNEE’S INFORMATION          收件人资料');
        for($i=1;$i<=10;$i++){
            $currentSheet->mergeCells('A'.$i.':G'.$i);
        }
        $currentSheet->setCellValue('A11', 'Receiver Address:');
        $currentSheet->mergeCells('A11:B11');
        $currentSheet->setCellValue('C11', 'Delivery(If different from receiver) ');
        $currentSheet->mergeCells('C11:G11');
        $currentSheet->setCellValue('A12', '');
        $currentSheet->mergeCells('A12:B12');
        $currentSheet->setCellValue('C12', 'COMPANY  NAME（收件公司名）：  '.$result['shipToAddress']['name']);
        $currentSheet->mergeCells('C12:G12');
        $currentSheet->mergeCells('A13:B15');
        $currentSheet->setCellValue('C13', "ADDRESS（收件公司地址）: ".$result['shipToAddress']['address']);
        $currentSheet->mergeCells('C13:G13');
        $currentSheet->setCellValue('C14', 'CONSIGNEE（收件人姓名）：'.$result['shipToAddress']['name']);
        $currentSheet->mergeCells('C14:G14');

        $currentSheet->setCellValue('C15', 'TEL（电话） ：');
        $currentSheet->mergeCells('C15:G15');
        $currentSheet->setCellValue('A16', 'NO.');
        $currentSheet->setCellValue('B16', "FULL  DESCRIPTION \n OF GOODS");
        $currentSheet->setCellValue('C16', 'HS  CODE');
        $currentSheet->setCellValue('D16', 'COUNTRY OF ORIGIN');
        $currentSheet->setCellValue('E16', 'QTY (PCS)');
        $currentSheet->setCellValue('F16', 'UNIT VALUE   (USD)');
        $currentSheet->setCellValue('G16', 'TOTAL VALUE    (USD)');
        $num = 16+count($result['sku']);
        foreach($result['sku'] as $y =>$v){
            $k = $y+17;
            $currentSheet->setCellValue('A'.$k, $v['sku']);
            $currentSheet->setCellValue('B'.$k, 'Crampons');
            $currentSheet->setCellValue('C'.$k, '95061900');
            $currentSheet->setCellValue('D'.$k, 'CN');
            $currentSheet->setCellValue('E'.$k, $v['quantity']);
            $currentSheet->setCellValue('H'.$k, $v['price']);
            $currentSheet->setCellValue('I'.$k, '=E'.$k.'*'.'H'.$k);
        }

        $currentSheet->setCellValue('A'.($num+1),'Total Invoice Value(USD)');
        $currentSheet->setCellValue('H'.($num+1),'=SUM(H17:H'.$num.')');
        $currentSheet->setCellValue('I'.($num+1),'=SUM(I17:I'.$num.')');
        $currentSheet->setCellValue('A'.($num+2),'THESE COMMODITIES ARE LICENSED FOR THE UNTIMATE DESTINATION SHOWN.');
        $currentSheet->setCellValue('G'.($num+2),'CHECK ONE');
        $currentSheet->setCellValue('A'.($num+3),'以上商品已有到最终目的地的许可。');
        $currentSheet->setCellValue('G'.($num+3),'□ F.O.B');
        $currentSheet->setCellValue('A'.($num+4),'');
        $currentSheet->setCellValue('G'.($num+4),'□ C.I.F');
        for($y=($num+1);$y<=($num+4);$y++){
            $currentSheet->mergeCells('A'.$y.':F'.$y);
        }
        $currentSheet->setCellValue('A'.($num+5),'I DECLARE ALL THE INFORMATION CONTAINED IN THIS INVOICE LIST TO BE TRUE AND CORRECT.');
        $currentSheet->mergeCells('A'.($num+5).':G'.($num+5));
        $currentSheet->setCellValue('A'.($num+6),'以上申报均属实。');
        $currentSheet->mergeCells('A'.($num+6).':G'.($num+6));
        $currentSheet->setCellValue('A'.($num+7),"SIGNATURE OF SHIPPER/EXPORTER(TYPE \n NAME TITLE AND SIGN):");
        $currentSheet->setCellValue('E'.($num+7),'DATE:');
        $currentSheet->setCellValue('F'.($num+7),date('Y.m.d'));
        $currentSheet->mergeCells('A'.($num+7).':C'.($num+7));
        $currentSheet->setCellValue('A'.($num+8),'寄件人/出口商签名( 正楷和职位)');
        $currentSheet->setCellValue('E'.($num+8),'日期');
        $currentSheet->setCellValue('F'.($num+8),date('Y.m.d'));
        $currentSheet->mergeCells('A'.($num+8).':C'.($num+8));
        $currentSheet->getRowDimension(13)->setRowHeight(84);
        $currentSheet->getRowDimension(16)->setRowHeight(29);
        $currentSheet->getRowDimension($num+2)->setRowHeight(33);
        $currentSheet->getRowDimension($num+7)->setRowHeight(34);
        $currentSheet->getStyle('A1')->getFont()->setSize(16);
        $currentSheet->getStyle('A1')->getFont()->setBold(true);
        $currentSheet->getStyle('A1')->getFont()->getColor()->setARGB(\PHPExcel_Style_Color::COLOR_DARKBLUE);
        $currentSheet->getStyle('A1')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $currentSheet->getStyle('A2')->getFont()->setSize(16);
        $currentSheet->getStyle('A2')->getFont()->setBold(true);
        $currentSheet->getStyle('A2')->getFont()->getColor()->setARGB(\PHPExcel_Style_Color::COLOR_DARKBLUE);
        $currentSheet->getStyle('A2')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $currentSheet->getStyle('A3')->getFont()->getColor()->setARGB(\PHPExcel_Style_Color::COLOR_DARKBLUE);
        $currentSheet->getStyle('A1:G'.($num+4))->getBorders()->getAllBorders()->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);
        $PHPWriter = new \PHPExcel_Writer_Excel2007($PHPExcel);
        /*目标投放文件名*/
        $outputFileName = $seller_name.' '.$shipmentid.' '.$site_id.' '.$result['box'].'箱.xlsx';
        ob_start();
        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header('Content-Disposition:attachment;filename="' .$outputFileName. '"');//输出模板名称
        header("Content-Transfer-Encoding: binary");
        header("Last-Modified:".gmdate("D, d M Y H:i:s")." GMT");
        header('Pragma: public');
        header('Expires: 30');
        header('Cache-Control: public');
        $PHPWriter->save('php://output');
    }

    /*
     * 获取箱唛信息
     */
    public function get_prepackge_label()
    {
        $this->condition = $_GET;
        $data            = $this->Inboundshipmentplan->select($_GET,TRUE);

        $this->assign('page',$this->Inboundshipmentplan->page);
        $this->assign('count',$this->Inboundshipmentplan->count);
        $this->assign('data',$data);
        $this->display();
    }

    /**
     *箱唛首页显示
     */
    public function package_box_index()
    {
        if($_GET)
        {
            C("LAYOUT_ON",FALSE);
            $this->condition = json_decode($_GET['data'],true);
            $this->Inboundshipmentplan->get_Inboundshipmentplan_detail($this->condition);
            if($this->Inboundshipmentplan->data[0]['status'] != '待录入箱唛数据')
            {
                echo json_encode(array('flag'=>1,'info'=>"状态不适合装箱"));return ;
            }

            $this->assign('data',$this->Inboundshipmentplan->data);

            $this->assign('inbound_shipment_plan_id',$this->Inboundshipmentplan->data[0]['aid']);

            echo json_encode($this->fetch("Inboundshipmentplan/plan_detail"));
            exit;
        }
        $this->display();
    }

    /**
     * 箱唛首页显示
     */
    public function package_box_index_bak()
    {
        if($_GET)
        {
            //C("LAYOUT_ON",FALSE);
            $this->condition = $_GET;
            $this->Inboundshipmentplan->get_Inboundshipmentplan_detail($this->condition);
            if($this->Inboundshipmentplan->data[0]['status'] != '待录入箱唛数据')
            {
                echo "<script>alert('状态不适合装箱！');window.location.href='package_box_index_bak'</script>";
            }
            $this->assign('data',$this->Inboundshipmentplan->data);
            $this->assign('inbound_shipment_plan_id',$this->Inboundshipmentplan->data[0]['aid']);
            $this->fetch("Inboundshipmentplan/plan_detail");
        }
        $this->display('package_box_index');
    }


    /*
 * 创建箱唛单
 * */
    public function create_package_box()
    {
        //print_r($_POST);exit;
        if($_POST)
        {
            $id = $this->packagebox->parse_package_data(json_decode($_POST['data'],true));
            echo json_encode($id);
        }
        //echo "string";exit;
    }

    /*
     * 创建箱唛表格
     * */
    public function create_prepackage_table()
    {
        C("LAYOUT_ON",FALSE);

        $this->assign('data',json_decode($_GET['data'],true));

        $content = $this->fetch('Packagebox/create_table');

        echo json_encode($content);
    }
    /*
     * 上传箱唛信息
     */
    public function upload_package(){
        set_time_limit(0);
        ini_set('memory_limit', '2048M');
        $file = $_FILES['fileName'];
        $max_size = "2000000"; //最大文件限制（单位：byte）
        $fname = $file['name'];
        $file_name = $file['tmp_name'];

        $sheet_data=PublicPlugService::parse_excel($file_name);

        //将二位数组插入到箱唛表中  待续
        $this->create($sheet_data);

    }

    /**
     * 更改箱唛信息
     */
    public  function update_package_info(){
        $info = $_POST;
        $res = $this->packagebox->update_package_info($info);
        if($res){

        }else{

        }
    }

    /*
     * 录入箱唛信息
     */
    public function add_package_info($packagebox_data)
    {
        $res = $this->packagebox->create($packagebox_data);
        if($res){

        }else{

        }
    }

    /**
     * 打印条形码
     */
    public function print_goods_code()
    {
        C('LAYOUT_ON',false);
        C('SHOW_PAGE_TRACE',false);
        $detail_id = trim($_GET['id']);
        $detail_id = explode(',',$detail_id);
        $data_all = array();
        foreach($detail_id as $id){
            $data = $this->Inboundshipmentplan->print_goods_code($id);
            $data_all = array_merge($data_all,$data);
        }

        if($data_all[0]['status']<=10){
            echo "<script>alert('亲，你还未推送仓库哦！');window.location.href='index'</script>";
            exit;
        }elseif($data_all[0]['status']==100){
            echo "<script>alert('该平台计划单已经取消！');window.location.href='index'</script>";
            exit;
        }

        $log = '';
        foreach($data_all as $key=>$details){
            if($details['title']==''){
                $log .= 'sku为：'.$details['sku'].' 的title为空。未打印sku有'.$details['sku'].'\r\n';
                unset($data_all[$key]);
            }
        }
        $this->assign('log',$log);
        $this->assign('detail_id',$_GET['id']);
        $this->assign('barcode',$this->barcode->barcodePrint($data_all));
        $this->display();
    }

    /**
     * 打印箱唛帖
     */
    public function print_prepackage(){
        C('LAYOUT_ON',false);
        $id = trim($_GET['id']);
        $shipmentid = trim($_GET['shipmentid']);
        $account_id = trim($_GET['account_id']);
        $this->condition = array('id'=>$id);
        $status = $this->Inboundshipmentplan->get_field_by_param($this->condition,array('status'));
        if($status[0]['status']<=30){
            echo "<script>alert('您还未装箱确认');window.location.href='index'</script>";
            exit;
        }elseif($status[0]['status']==100){
            echo "<script>alert('该平台计划单已经取消！');window.location.href='index'</script>";
            exit;
        }

        //查出计划单箱唛数
        $this->condition = array('inbound_shipment_plan_id'=>$id);
        $num = $this->packagebox->packageboxdetails->Packagebox->where($this->condition)->count();
        if(empty($num)){
            echo "<script>alert('您还未录入箱唛数据');window.location.href='index'</script>";
            exit;
        }
        //$account_id = 19;
        $options = array(
            'ShipmentId' => $shipmentid,
            //'ShipmentId' => 'FBAZ5GTX0',
            'PageType' => 'PackageLabel_Plain_Paper',
            'NumberOfPackages' => $num,
        );
        //接口
        $shipmentidList = $this->API_Inbound->getPackageLabels($account_id, $options);
        if($shipmentidList['status'] == 500 ){
            echo "<script>alert('".$shipmentidList['msg']."');window.location.href='index'</script>";
            exit;
        }
        $file    = 'Public/uploads/' . 'test.zip';
        $file    = str_replace('','',$file);
        $fp      = fopen($file,'w',1);
        fputs($fp,base64_decode($shipmentidList['msg']['PdfDocument']));
        fclose($fp);
        $zip = zip_open($file);
        if($zip){
            while ($zip_entry = zip_read($zip)){
                #预览pdf
                $name = time();
                zip_entry_open($zip,$zip_entry);
                $tpdf = zip_entry_read($zip_entry,zip_entry_filesize($zip_entry));
                $file = 'Public/uploads/' .$name.'.pdf';
                $file = str_replace('','',$file);
                $fp   = fopen($file,'w');
                fputs($fp,$tpdf);
                fclose($fp);
                $file = 'Public/uploads/' .$name.".pdf";
                $save = array(
                    'package_pdf_path'       => $file,
                    'package_print_user_id' => $_SESSION['current_account']['role_id'],
                    'package_print_time'    => $this->Inboundshipmentplan->nowtime,
                );
                $this->Inboundshipmentplan->update(array('id'=>$id),$save);
                header('Content-type: application/pdf');
                header('filename='.$file);
                readfile($file);
                exit;
                //下载
                //header('Content-Type:pdf'); //指定下载文件类型
                //header('Content-Disposition: attachment; filename="'.$filename.'"'); //指定下载文件的描述
                //header('Content-Length:'.filesize($filename)); //指定下载文件的大小
                //eadfile($filename);
            }
        }
//        print_r($shipmentidList);
        exit;
    }

    /**
     * 捡货单页面显示
     */
    public function pick_goods(){
        C('LAYOUT_ON',false);
        C('SHOW_PAGE_TRACE',false);
        $ids = rtrim($_GET['ids'],',');
        $this->condition = "id in ({$ids})";
        $data = $this->Inboundshipmentplan->select($this->condition,FALSE);
        //dump($data);die;
        $log = '';
        foreach($data as $key=>$send){

            if($send['status']=='待推送仓库'){
                $log .= 'shipmentId为：'.$send['shipmentid'].' 的FBA平台计划单还未推送仓库. '.'\r\n';
                unset($data[$key]);
            }elseif($send['status']=='取消'){
                $log .= 'shipmentId为：'.$send['shipmentid'].' 的FBA平台计划单已经取消. '.'\r\n';
                unset($data[$key]);
            }
        }
        $this->assign('log',$log);
        $this->assign('ids',$ids);
        $this->assign('data',$data);
        $this->display();
    }
    /**
     * 添加修改打印捡货单人以及打印时间
     */
    public function updatePrint()
    {
        $ids = I('post.id');
        $data = $this->Inboundshipmentplan->updatePrint($ids);
        if ($data) {
            $this->ajaxReturn(1);
        } else {
            $this->ajaxReturn(0);
        }
    }

    /**
     * 更新状态
     * 推送仓库
     */
    public function update_plan_and_datail_status(){
        $ids = rtrim($_GET['ids'],',');
        $status = trim($_GET['status']);
        $status_to = trim($_GET['statusto']);
        $this->condition = "id in ({$ids})";
        $status_arr = $this->Inboundshipmentplan->Inboundshipmentplandetail->get_field_by_param($this->condition,array('status'));
        $log = '';
        foreach($status_arr as $sta){
            if($sta['status']==$status){
                $res = $this->Inboundshipmentplan->update_plan_status($status,$status_to,$this->condition);
                if($res){
                    echo json_encode(array('msg'=>'操作成功'));
                    exit;
                }else{
                    echo json_encode(array('msg'=>'操作失败'));
                    exit;
                }
            }else{
                $log = '该状态不能进行该操作<br/>';
                echo json_encode(array('msg'=>$log));
                exit;
            }
        }
    }

    /**
     * 更新状态
     * 装箱确认
     */
    public function update_plan_and_datail_status_prepackage(){
        $ids = rtrim($_GET['ids'],',');
        $status = trim($_GET['status']);
        $status_to = trim($_GET['statusto']);
        $this->condition = "id in ({$ids})";
        $status_arr = $this->Inboundshipmentplan->Inboundshipmentplandetail->get_field_by_param($this->condition,array('status'));
        $log = '';
        foreach($status_arr as $sta){
            if($sta['status']==$status){
                $res = $this->Inboundshipmentplan->update_plan_status($status,$status_to,$this->condition);
                if($res){
                    echo json_encode(array('msg'=>'操作成功'));
                    exit;
                }else{
                    echo json_encode(array('msg'=>'操作失败'));
                    exit;
                }
            }else{
                $log = '该状态不能进行该操作<br/>';
                echo json_encode(array('msg'=>$log));
                exit;
            }
        }
    }

    /**
     * 取消平台计划单
     */
    public function cancel(){
        $this->condition = array('id'=>trim($_GET['id']));

        $status = $this->Inboundshipmentplan->get_field_by_param($this->condition,'status');
        $this->status_prompt($status[0]['status'],10);

        $id = trim($_GET['id']);
        $account_id = trim($_GET['account_id']);
        $shipmentId = trim($_GET['shipmentid']);
        $res = $this->API_Inbound->delInboundShipment($account_id,$shipmentId);
        if($res==$shipmentId){
            $this->condition = array('id'=>$id);
            $this->Inboundshipmentplan->update_plan_status(10,100,$this->condition);
            //取消时更改prepare_needs_details_shipmentid表的状态
            $this->Inboundshipmentplan->updata_prepare_needs_details_shipmentid($shipmentId);
            echo "<script>alert('您已取消成功！');window.location.href='index'</script>";
            exit;
        }else{
            echo "<script>alert('api借口调用失败,".$res['msg']."');window.location.href='index'</script>";
            exit;
        }
    }
    /**
     * 编辑平台计划单
     */
    public function edit(){
        $id = trim($_POST['id']);
        $account_id = trim($_POST['account_id']);
        $site = trim($_POST['site']);
        $shipmentid = trim($_POST['shipmentid']);
        $destination_fullfillment_center_id = trim($_POST['destination_fullfillment_center_id']);
        $seller_sku_str = explode(';',rtrim($_POST['seller_sku_str'],';'));
        $datail_id_str = explode(';',rtrim($_POST['datail_id_str'],';'));
        $quantity_str = explode(';',rtrim($_POST['quantity_str'],';'));
        $fnsku_str = explode(';',rtrim($_POST['fnsku_str'],';'));

        //接口数据
        $InboundShipmentItems = array();
        for($i=0;$i<count($quantity_str);$i++){
            $send_arr = array(
                'ShipmentId' => $shipmentid,
                'FulfillmentNetworkSKU' => $fnsku_str[$i],
                'QuantityShipped' => $quantity_str[$i],
                'SellerSKU' => $seller_sku_str[$i],
            );
            $InboundShipmentItems[] = $send_arr;
        }
        $options = array(
            'ShipmentId' => $shipmentid,
            'InboundShipmentHeader' => array(
                'ShipmentName' => time(),
                'DestinationFulfillmentCenterId' => $destination_fullfillment_center_id,
                'LabelPrepPreference' => 'SELLER_LABEL',
                'AreCasesRequired' => false,
                'ShipmentStatus' => 'WORKING',
            ),
            'InboundShipmentItems' => $InboundShipmentItems,
        );
        //1.先修改平台sku的数量,美国站不调用api
        if($site != 'US'){
            $shipmentIdList = $this->API_Inbound->updateInboundShipment($account_id, $options);
        }
        //2.更改本地的sku数量
        if(!is_array($shipmentIdList) || $site == 'US'){
            $res = array();
            foreach($datail_id_str as $key=>$detail_id){
                $this->condition = array('inbound_shipment_plan_id'=>$id,'id'=>$detail_id);
                $obj = $this->Inboundshipmentplan->Inboundshipmentplandetail
                    ->update_detail($this->condition,array('quantity'=>$quantity_str[$key]));
                $res[] = $obj;
            }
            if(in_array(1,$res)){
                //计划单详情数量全部为0则修改状态
                $this->Inboundshipmentplan->updateStatusForDetailQuantity($id);
                $msg = array(
                    'status'=>200,
                    'msg'=>'操作成功'
                );
            }else{
                $msg = array(
                    'status'=>400,
                    'msg'=>'操作失败'
                );
            }
        }else{
            $msg = array(
                'status'=>500,
                'msg'=>'API错误：'.$shipmentIdList['msg']
            );
        }
        $this->ajaxReturn($msg);
    }
    /**
     * 平台sku列表
     */
    public function show_sku_info(){
        $sellerSkuService = D('Api/Amazon/AccountSellerSku','Service');
        $SitesService = D('Api/Amazon/Sites','Service');
        $statusName = PublicInfoService::getSaleStatusName();
        $data = array();
        if ($_GET) {
            $data = $sellerSkuService->selectSku($_GET,TRUE);
            $site = PublicInfoService::get_site_array();//显示简码
            foreach($data as $k =>$v){
                $data[$k]['site_id'] = $site[$v['site_id']];
                $data[$k]['add_user_id'] = PublicInfoService::get_user_name_by_id($v['add_user_id']);
                $data[$k]['account_id'] = PublicInfoService::get_accounts_by_id($v['account_id'],'name');
                $data[$k]['statusName'] = $statusName[$data[$k]['sale_status_id']];
            }
        }
        $role = array(1,5,27,28,35);
        //判断是否采购
        if(in_array($_SESSION['current_account']['role_id'],$role)){
            $up = 200;
        }else{
            $up = 300;
        }
        $this->assign('site',$SitesService->getSites());
        $this->assign('accounts',$this->accounts);
        $this->assign('is_up',$up);
        $this->assign('saleStatus', $this->saleStatus);
        $this->assign('page',$sellerSkuService->page);
        $this->assign('count',$sellerSkuService->count);
        $this->assign('data',$data);
        $this->display();
    }
    /**
     * 新增SKU
     */
    public function addSku(){
        if(!I('post.privateSku')){
            $this->ajaxReturn("公司内部sku不能为空");
            die;
        }
        if(!I('post.sellerSku')){
            $this->ajaxReturn("sellerSku不能为空");
            die;
        }
        if(!I('post.FNsku')){
            $this->ajaxReturn("FNsku不能为空");
            die;
        }
        if(!I('post.asin')){
            $this->ajaxReturn("ASIN不能为空");
            die;
        }
        if(!I('post.accountId')){
            $this->ajaxReturn("帐号不能为空");
            die;
        }
        if(!I('post.siteId')){
            $this->ajaxReturn("站点不能为空");
            die;
        }
//        if(!I('post.firsttime')){
//            $this->ajaxReturn("首次入库时间不能为空");
//            die;
//        }
        $data = I('post.');
        $sellerSkuService = D('Api/Amazon/AccountSellerSku','Service');
        $check = $sellerSkuService->accountIdAndSellerSku(I('post.accountId'),trim(htmlspecialchars_decode(I('post.sellerSku'))));
        if(!$sellerSkuService->checkSku(trim(I('post.privateSku')))){
            $this->ajaxReturn("公司内部不存在".I('post.privateSku')."这个SKU");
            die;
        }

        if($check){
            $this->ajaxReturn("此帐号的sellersku已存在");
            die;
        }else{
            $result = $sellerSkuService->addSku($data);
            if($result){
                $this->ajaxReturn(1);
                die;
            }else{
                $this->ajaxReturn("新增失败");
                die;
            }
        }

    }
    /**
     * 废除SKU
     */
    public function delSku(){
        $data = I('post.id');
        if(!$data){
            $ret = '请选择数据！';
        }else{
            $sellerSkuService = D('Api/Amazon/AccountSellerSku','Service');
            $ret = $sellerSkuService->delSku($data);
        }
        $this->ajaxReturn($ret);
    }
    /**
     *编辑sku
     */
    public function updateSku(){
        if(!I('post.privateSku')){
            $this->ajaxReturn("公司内部sku不能为空");
            die;
        }
        if(!I('post.sellerSku')){
            $this->ajaxReturn("sellerSku不能为空");
            die;
        }
        if(!I('post.FNsku')){
            $this->ajaxReturn("FNsku不能为空");
            die;
        }
        if(!I('post.asin')){
            $this->ajaxReturn("ASIN不能为空");
            die;
        }
        if(!I('post.accountId')){
            $this->ajaxReturn("帐号不能为空");
            die;
        }
        if(!I('post.siteId')){
            $this->ajaxReturn("站点不能为空");
            die;
        }
//        if(!I('post.firsttime')){
//            $this->ajaxReturn("首次入库时间不能为空");
//            die;
//        }
        $sellerSkuService = D('Api/Amazon/AccountSellerSku','Service');
        if(!$sellerSkuService->checkSku(trim(I('post.privateSku')))){
            $this->ajaxReturn("公司内部不存在".I('post.privateSku')."这个SKU");
            die;
        }
        $data = I('post.');
        $accountSellerSkuModel = D('Api/Amazon/AccountSellerSku','Model');
        $id = trim($data['id']);
        $where['account_id'] = trim($data['accountId']);
        $where['seller_sku'] = htmlspecialchars_decode(trim($data['sellerSku']));
        $check = $accountSellerSkuModel->where($where)->getField('id');

        if($check && $check != $id){
            $this->ajaxReturn("此帐号的seller_sku已存在");
            die;
        }
        $sellerSkuService = D('Api/Amazon/AccountSellerSku','Service');
        $result = $sellerSkuService->updateSku($data);
        if($result){
            $this->ajaxReturn(1);
            die;
        }else{
            $this->ajaxReturn("修改失败");
            die;
        }
    }
    /**
     * 导出sku模板
     * khq 2016.12.29
     */
    public function skuDownload()
    {
        set_time_limit(0);
        if (I('get.accountId')){
            $accountId = I('get.accountId');
            $where = "account_id = '$accountId' AND (fnsku = '' or private_sku = '' or asin = '') AND is_used = 1";
            $data = M('account_seller_sku','api_','DB_FBAERP')->where($where)->select();
            if(count($data)==0){
                echo "<script>alert('没有需要更新的sku');history.go(-1);</script>";die;
            }
            vendor('PHPExcel.PHPExcel');
            /*模板存放目录*/
            $templateFile = realpath(__ROOT__) . '/Admin/Inbound/Template/' . date('Y-m-d',time());
            $accountName = PublicInfoService::get_accounts_by_id($accountId,'name');
            /*目标投放文件名*/
            $outputFileName = date('md').$accountName.'需要更新的sku.xlsx';
            $PHPExcel = new \PHPExcel();
            //$PHPReader = new \PHPExcel_Reader_Excel2007();

            $currentSheet = $PHPExcel->getSheet(0);
            $currentSheet->setCellValue('A1','帐号名称');
            $currentSheet->setCellValue('B1','SellerSku');
            $currentSheet->setCellValue('C1', 'FNSKU');
            $currentSheet->setCellValue('D1', "公司内部SKU");
            $currentSheet->setCellValue('E1', "ASIN");
            $currentSheet->setCellValue('F1', "title");
            foreach($data as $x =>$v){
                $y = $x+2;
                $currentSheet->setCellValue('A'.$y,$accountName);
                $currentSheet->setCellValue('B'.$y,$v['seller_sku']);
                $currentSheet->setCellValue('C'.$y,$v['fnsku']);
                $currentSheet->setCellValue('D'.$y, $v['private_sku']);
                $currentSheet->setCellValue('E'.$y, $v['asin']);
                $currentSheet->setCellValue('F'.$y, $v['title']);

            }
            $PHPWriter = new \PHPExcel_Writer_Excel2007($PHPExcel);
            ob_start();
            header("Content-Type: application/force-download");
            header("Content-Type: application/octet-stream");
            header("Content-Type: application/download");
            header('Content-Disposition:attachment;filename="' .$outputFileName. '"');//输出模板名称
            header("Content-Transfer-Encoding: binary");
            header("Last-Modified:".gmdate("D, d M Y H:i:s")." GMT");
            header('Pragma: public');
            header('Expires: 30');
            header('Cache-Control: public');
            $PHPWriter->save('php://output');
            die;
        }else{
            PublicPlugService::download_templet_xlsx();
        }

    }

    /*
     * 描述：下载所有sellerSKU与公司SKU对应关系
     */
    public function downloadAllSku() {
        $sellerSkuService = D('Api/Amazon/AccountSellerSku','Service');
        $sku = $sellerSkuService->downloadAllSku();
        $firstLine = array(
            'name'                => "账号名称",
            'shorthand_code'      => "站点",
            'seller_sku'          => "SellerSku",
            'private_sku'         => "公司SKU",
            'asin'                => "ASIN",
            'fnsku'               => "FNSKU",
            'first_received_date' => "FBA首次入库时间",
            'value'               => "销售状态",
            'is_used'             => "是否可用",
        );
        $fileName = "SellerSKU信息表";
        $this->Prepareneeds->download_function($sku, $firstLine, $fileName);
    }

    /**
     * 上传sku
     */
    public function upload_sku()
    {
        $sellerSkuService = D('Api/Amazon/AccountSellerSku','Service');
        $sheetData = PublicPlugService::parse_excel();                            //解析excel内容
        if(!$sheetData) {
            echo "<script>alert('文件内容解析有误，请检查文件内容');history.go(-1)</script>";
            exit;
        }
        if(!PublicPlugService::$flag){                                            //选择了上传文件,状态返回false
            if(count($sheetData)>=2){
                $isUpStatus = isset($_GET['upStatus']) ? intval($_GET['upStatus']) : 0;
                $check_data = $sellerSkuService->check_upload_data($sheetData, $isUpStatus); // 检查导入的备货需求数据合法性
                if(!$check_data['status']){
                    echo "<script>alert('".$check_data['message']."');history.go(-1)</script>";
                    exit;
                }
                if ($isUpStatus) {
                    $result = $sellerSkuService->undate_sale_status($sheetData);
                } else {
                    $result = $sellerSkuService->upload_platform($sheetData);//最后解析数据,验证,更新数据库
                }
                echo "<script>alert('".$result."');window.location.href = 'show_sku_info'</script>";die;
            }else{
                echo "<script>alert('文件内容为空');history.go(-1)</script>";die;
            }
        }else{
            echo '<script>alert("请选择上传文件");history.go(-1)</script>';die;
        }
    }
    /**
     * 拉取title
     * */
    public function getTitle(){
        $sellerSkuService = D('Api/Amazon/AccountSellerSku','Service');
//        $accountId = I('get.accountId');
//        if(!$accountId){
//            echo "<script>alert('请选择帐号');window.location.href = 'show_sku_info'</script>";
//            die;
//        }
//        $result = $sellerSkuService->getTitle($accountId);
//        if($result){
//            echo "<script>alert('拉取title成功');window.location.href = 'show_sku_info'</script>";die;
//        }else{
//            echo "<script>alert('拉取title失败，请检查后操作');window.location.href = 'show_sku_info'</script>";die;
//        }
        $accountId = I('post.accountId');
        if(!$accountId){
            $this->ajaxReturn('请选择帐号');
            die;
        }
        $site = PublicInfoService::get_siteid_by_accountid($accountId);
        if($site == '55'){
            $this->ajaxReturn('日本站点暂时使用不了此功能，请抱歉');
            die;
        }
        $result = $sellerSkuService->getTitle($accountId);
        if($result){
            $this->ajaxReturn($result);
//            $this->ajaxReturn('拉取title成功');
            die;
        }else{
            $this->ajaxReturn($result);
//            $this->ajaxReturn('拉取title失败，请检查后操作');
            die;
        }

    }
    /**
     * 抓取页面显示
     */
    public function get_by_shipmentid(){

        $this->assign('batch_code',$this->Prepareneeds->select_batch_code());
        $this->assign('accounts',$this->accounts);
        $this->assign('transport_way',PublicInfoService::get_transport_way_array());
        $this->assign('enterprise_dominant',PublicInfoService::get_company_array());
//        dump(D('Api/Amazon/ShipToAddress','Service')->getOrInsertShipToAddress(79));exit;
//        $this->assign('ship_to_address_id',D('Api/Amazon/ShipToAddress','Service')->getOrInsertShipToAddress(62));

        $this->display();
    }

    /**
     *平台计划单的抓取
     *
     */
    public function grab_shipment_plan(){
        if(isset($_GET['shipmentid']) && $_GET['shipmentid']!=''){
            $accountid = trim($_GET['accountid']);
            $shipmentid = trim($_GET['shipmentid']);
            //查询系统中是否存在该shipment
            $this->condition = array('account_id'=>$accountid,'shipmentid'=>$shipmentid);
            $if_exist = $this->Inboundshipmentplan->get_field_by_param($this->condition,array('id'));

            if(empty($if_exist)){
                $options1 = array(
                    'ShipmentId' => $shipmentid,
                );
                $options2 = array(
                    'ShipmentIdList' => $shipmentid,
                );
                $plan = $this->API_Inbound->listInboundShipmentItems($accountid,$options1);
                $plan_address = $this->API_Inbound->listInboundShipments($accountid,$options2);

                $return_data = $this->Inboundshipmentplan->grab_shipment_plan($_GET,$plan,$plan_address);

                S('plan_and_detail_data',$return_data,3600);

                $this->assign('ship_to_address_id',D('Api/Amazon/ShipToAddress','Service')->getOrInsertShipToAddress($accountid));
                $this->assign('transport_way',PublicInfoService::get_transport_way_array());
                $this->assign('enterprise_dominant',PublicInfoService::get_company_array());
                $this->assign('plan_and_detail_data',$return_data);
                $this->assign('batch_code',$this->Prepareneeds->select_batch_code());
                $this->assign('accounts',$this->accounts);
                $this->display('get_by_shipmentid');
            }else{
                echo "<script>alert('该平台计划单已经存在');window.location.href='get_by_shipmentid'</script>";
                exit;
            }
        }else{
            $return_data ='';
        }
    }

    /**
     * 新增地址
     */
    public function add_address(){
        $accountid = trim($_POST['accountid']);
        $address   = nl2br(trim($_POST['address']),false);
        $ship_to_address = D('Api/Amazon/ShipToAddress','Service')->getOrInsertShipToAddressForUs($accountid,$address);
        if($ship_to_address ==false){
            echo json_encode(array('status'=>4));
        }else{
            echo json_encode(array('status'=>5,'ship_to_address_id'=>$ship_to_address,'address'=>$address));
        }
    }

    /**
     *抓取确认
     */
    public function grab_confirm(){
        $plan_and_detail_data = S(plan_and_detail_data);
        if($plan_and_detail_data){
            $res = $this->Inboundshipmentplan->grab_confirm($_POST,$plan_and_detail_data);
            if ($res == 404) {
                echo json_encode(array('msg'=>'ShipmentId已存在'));
                exit;
            } elseif ($res == 200) {
                echo json_encode(array('msg'=>'操作成功'));
                exit;
            } else {
                echo json_encode(array('msg'=>'操作失败'));
                exit;
            }
        } else {
            echo json_encode(array('msg'=>'操作失败'));
            exit;
        }
    }
    /**
     * 根据批次号获取备货单详情
     */
    public function get_prepareneedsdetail(){
        $sku  = rtrim($_POST['sku'],',');
        $batch_code = trim($_POST['batch_code']);
        $accountid = trim($_POST['accountid']);
        $carrier_service_id = $_POST['carrier_service_id']?trim($_POST['carrier_service_id']):array('NEQ', 0);
        $this->condition=array(
            'sku'=>array('in',$sku),
            'batch_code'=>$batch_code,
            'account_id'=>$accountid,
            'carrier_service_id'=>$carrier_service_id,
            'status'=>array('NEQ', 100)
        );
        $batch_sku = $this->Prepareneeds->prepareneedsdetail->prepareNeedsDetails
            ->where($this->condition)
            ->field('id,sku,needs_quantity,export_tax_rebate,carrier_service_id,claim_arrive_time,enterprise_dominant')
            ->order('claim_arrive_time asc')
            ->select();
        $batchsku = $this->Inboundshipmentplan->format_prepareneeds_data($batch_sku);
        $str = '';
        foreach ($batchsku as $k){
            $str =  $k['carrier_service_id'].',';
        }
        $arr = (explode(',', rtrim($str,',')));
        $flag = count(array_unique($arr));
        if($flag>1){
            $flag = 0;
        }else{
            $flag = 1;
        }
        echo json_encode(array('sku'=>$batchsku,
            'flag'=>$flag,
            'min_claim_arrive_time'=>$batchsku[0]['claim_arrive_time'],
            'carrier_service_id'=>$arr[0]
        ));
        exit;
    }

    /*
     *状态提示
     */
    public function status_prompt($status,$status_now){
        if($status!=$status_now){
            echo "<script>alert('当前状态，无法操作！');window.location.href='index'</script>";
            exit;
        }elseif($status==100){
            echo "<script>alert('改平台计划单已经取消！');window.location.href='index'</script>";
            exit;
        }
    }

    /**
     * 下载箱唛数据
     */
    public function inboundBoxDown(){
        $inboundPlanId = I('post.inboundPlanId', 0);

        $downFlag = 0;
        $inboundShipmentBoxInfo = $this->Inboundshipmentplan->getShipmentInboundBoxInfo ($inboundPlanId);
        if(is_array($inboundShipmentBoxInfo) && empty($inboundShipmentBoxInfo)) {
            /*无装箱数据*/
            $downFlag = 1;
        } elseif ($inboundShipmentBoxInfo === false) {
            /*系统数据异常*/
            $downFlag = 2;
        }

        if($downFlag > 0) {
            echo $downFlag;
            exit;
        }

        vendor('PHPExcel.PHPExcel');

        $packageBoxNumber = count($inboundShipmentBoxInfo['packages']);
        $planDetailsNumber = count($inboundShipmentBoxInfo['planDetails']);

        /*模板存放目录*/
        $templateFileName = $this->Inboundshipmentplan->getSiteTemplateName($inboundShipmentBoxInfo['site_id']);
        $templateFile = realpath(__ROOT__) . '/Admin/Inbound/Template/' . $templateFileName;
        //$templateFile = '/var/www/fbawarehouse'. '/Admin/Inbound/Template/' . $templateFileName;

        /*目标投放文件名*/
        $outputFileName = $inboundShipmentBoxInfo['shipmentid'] . '.xlsx';

        $PHPReader = new \PHPExcel_Reader_Excel2007();
        $PHPExcel = $PHPReader->load($templateFile);
        $currentSheet = $PHPExcel->getSheet(0);

        //->getDefaultStyle()->getFont()->setSize(20);
        $currentSheet->setCellValue('B1', $inboundShipmentBoxInfo['shipmentid']);
        $currentSheet->setCellValue('A2', 'Name:' . $inboundShipmentBoxInfo['shipmentName']);
        if($planDetailsNumber != 1){
            $currentSheet->insertNewRowBefore(6, $planDetailsNumber - 1);
        }
        /*设置计划明细标题*/
        $beginCode = 'L';
        for($i = 1; $i <= $packageBoxNumber; $i ++) {
            $currentSheet->setCellValue($beginCode . '4', 'Box ' . $i . ' - QTY');
            if($templateFileName == 'InboundBoxTemplate_Europe.xlsx')
                $currentSheet->setCellValue($beginCode . (6 + $planDetailsNumber), 'Box ' . $i);
            //$beginCode = chr(ord($beginCode) + 1);

            $beginCode ++;

        }

        /*添加计划明细*/
        $rowNumber = 5;
        foreach ($inboundShipmentBoxInfo['planDetails'] as $planDetail) {
            $currentSheet->setCellValue('A' . $rowNumber, $planDetail['sellerSku']);
            $currentSheet->setCellValue('B' . $rowNumber, isset($inboundShipmentBoxInfo['asin'][$planDetail['sellerSku']]) ? $inboundShipmentBoxInfo['asin'][$planDetail['sellerSku']] : '');
            $currentSheet->setCellValue('C' . $rowNumber, $planDetail['title']);
            $currentSheet->setCellValue('D' . $rowNumber, $planDetail['fnsku']);
            $currentSheet->setCellValue('E' . $rowNumber, $planDetail['externalId']);
            $currentSheet->setCellValue('F' . $rowNumber, 'None Required');
            $currentSheet->setCellValue('G' . $rowNumber, '--');
            $currentSheet->setCellValue('H' . $rowNumber, 'Merchant');
            $currentSheet->setCellValue('I' . $rowNumber, $planDetail['quantity']);
            $currentSheet->setCellValue('J' . $rowNumber, $planDetail['quantity']);

            $planBoxBegin = 'L';
            foreach ($inboundShipmentBoxInfo['packages'] as $packageId=>$package) {
                if(isset($inboundShipmentBoxInfo['packageDetails'][$planDetail['sellerSku']][$packageId]))
                    $currentSheet->setCellValue($planBoxBegin . $rowNumber,
                        $inboundShipmentBoxInfo['packageDetails'][$planDetail['sellerSku']][$packageId]);

                //$planBoxBegin = chr(ord($planBoxBegin) + 1);

                $planBoxBegin ++;
            }

            /*设置行高*/
            $currentSheet->getRowDimension($rowNumber)->setRowHeight(21);

            $rowNumber ++;
        }

        /*设置汇总信息*/
        $currentSheet->setCellValue('A' . (6 + $planDetailsNumber), 'Plan ID:');
        $currentSheet->setCellValue('A' . (7 + $planDetailsNumber), 'Ship To: ' . $inboundShipmentBoxInfo['shipToAddressCenterId']);
        $currentSheet->setCellValue('A' . (8 + $planDetailsNumber), 'Total SKUs: ' . $planDetailsNumber);
        $currentSheet->setCellValue('A' . (9 + $planDetailsNumber), 'Total Units: ' . $inboundShipmentBoxInfo['totalNum']);


        /*设置箱唛数据*/
        if($templateFileName == 'InboundBoxTemplate_Europe.xlsx') {
            $boxBegin = 'L';
            foreach ($inboundShipmentBoxInfo['packages'] as $packageId => $package) {
                $currentSheet->setCellValue($boxBegin . (7 + $planDetailsNumber), $package['weight']);
                $currentSheet->setCellValue($boxBegin . (8 + $planDetailsNumber), $package['length']);
                $currentSheet->setCellValue($boxBegin . (9 + $planDetailsNumber), $package['width']);
                $currentSheet->setCellValue($boxBegin . (10 + $planDetailsNumber), $package['height']);

                //$boxBegin = chr(ord($boxBegin) + 1);

                $boxBegin ++;
            }
        }

        $PHPWriter = new \PHPExcel_Writer_Excel2007($PHPExcel);
        ob_start();
        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header('Content-Disposition:attachment;filename="' .$outputFileName. '"');//输出模板名称
        header("Content-Transfer-Encoding: binary");
        header("Last-Modified:".gmdate("D, d M Y H:i:s")." GMT");
        header('Pragma: public');
        header('Expires: 30');
        header('Cache-Control: public');
        //        $PHPWriter->save('php://output');
        $PHPWriter->save(realpath(__ROOT__). '/Public/package/' . $outputFileName);
        //$PHPWriter->save('/var/www/fbawarehouse'. '/Public/package/' . $outputFileName);
        echo json_encode(array('fileName'=>$outputFileName));
        exit;
    }

    /**
     * 下载文件
     */
    public function downInboundBoxXlsx () {
        set_time_limit(0);
        header('Content-Type: application/download'); //下载头
        header('Content-Transfer-Encoding: binary'); //二进制
        header('Content-Disposition: attachment; filename='.I('get.fileName')); //文件名
        header('Pragma:no-cache'); //不缓存

        $path = realpath(__ROOT__) . '/Public/package/' . I('get.fileName');
        $fp   = fopen($path,'r');
        flock($fp,LOCK_SH); //加共享锁
        while(!feof($fp)){ //读取数据
            echo fread($fp,8192);
        }
        fclose($fp);

        exit;
    }
    /**
     *装箱查询
     * kelvin 2017-02-25
     */
    public function select_package_info(){
        set_time_limit(0);
        $this->condition = $_GET;
        $data            = $this->Inboundshipmentplan->packageSelect($_GET,TRUE);
        $this->assign('accounts',$this->accounts);
        $this->assign('page',$this->Inboundshipmentplan->page);
        $this->assign('count',$this->Inboundshipmentplan->count);
        $this->assign('data',$data);
        $this->display();
    }
    /**
     * 粘贴防火标示
     * */
    public function doFire(){
        $data = I('post.id');
        if(!$data){
            $ret = '请选择数据！';
        }else{
            $ret = $this->Inboundshipmentplan->doFire($data);
        }
        $this->ajaxReturn($ret);
    }
    /**
     * 描述: 删除装箱数据
     * 作者: kelvin
     */
    public function boxDel() {
        $data = I('post.');
        if(!$data['id'] || !$data['shipmentid']){
            $ret = '请选择数据！';
        }else{
            $status = M('inbound_shipment_plan','fba_','DB_FBAERP')
                ->where("shipmentid = '".$data['shipmentid']."'")
                ->getField('status');
            if($status < 50 ){
                $ret = $this->Inboundshipmentplan->boxDel($data);
            }else{
                $ret = '该状态不能删除装箱数据！';
            }

        }
        $this->ajaxReturn($ret);
    }
    /**
     * 下载装箱数据
     */
    public function download_box(){
        set_time_limit(0);
        $id=I('get.id');
        $shipmentid=trim(I('get.shipmentid'));
        $load = $this->Inboundshipmentplan->select(array('shipmentid'=>$shipmentid),TRUE);
        $package_box_id = M('package_box','fba_','DB_FBAERP')->where("id in ($id)")->select();
        foreach($package_box_id as $k =>$v){
            $data[$k]['detail'] = M('package_box_details','fba_','DB_FBAERP')->where("package_box_id = ".$v['id'])->select();
            foreach($data[$k]['detail'] as $a =>$c) {
                $data[$k]['detail'][$a]['enterprise_dominant'] = $this->Inboundshipmentplan->getEnterprise($data[$k]['detail'][$a]['inbound_shipment_plan_id'],$data[$k]['detail'][$a]['sku']);
                $data[$k]['detail'][$a]['export_tax_rebate'] = $v['export_tax_rebate'];
            }
            $data[$k]['weight'] = $v['weight'];
            $data[$k]['size'] = $v['length'].'*'.$v['width'].'*'.$v['height'];
            
        }
        //$data = M('package_box_details','fba_','DB_FBAERP')->where("package_box_id = $id")->select();
        $num = count($data);
//        dump($data);die;
        vendor('PHPExcel.PHPExcel');
        /*模板存放目录*/

        $templateFile = realpath(__ROOT__) . '/Admin/Inbound/Template/' . date('Y-m-d',time());
        //$templateFile = '/var/www/fbawarehouse'. '/Admin/Inbound/Template/' . $templateFileName;

        /*目标投放文件名*/
        $outputFileName = $load[0]['seller_name'].' '.$shipmentid.' '.$load[0]['site_id'].' '.$num.'箱.xlsx';
        $PHPExcel = new \PHPExcel();
        //$PHPReader = new \PHPExcel_Reader_Excel2007();

        $currentSheet = $PHPExcel->getSheet(0);
        $PHPExcel->getDefaultStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
        $PHPExcel->getDefaultStyle()->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $currentSheet->getStyle('A1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $currentSheet->getColumnDimension('A')->setWidth(20);
        $currentSheet->getColumnDimension('B')->setWidth(20);
        $currentSheet->getColumnDimension('C')->setWidth(20);
        $currentSheet->getColumnDimension('D')->setWidth(20);
        $currentSheet->getColumnDimension('E')->setWidth(20);
        $currentSheet->getColumnDimension('F')->setWidth(20);
        $currentSheet->mergeCells('A1:H1');
        $currentSheet->setCellValue('A1','Package list');
        $currentSheet->setCellValue('A2','Case NO.');
        $currentSheet->setCellValue('B2', 'Item NO.');
        $currentSheet->setCellValue('C2', "Discription");
        $currentSheet->setCellValue('D2', "Quantity\n(PCS)");
        $currentSheet->setCellValue('E2', "G.W\n(KG)");
        $currentSheet->setCellValue('F2', "CTN.Size\n(cm)");
        $currentSheet->setCellValue('G2', "是否退税");
        $currentSheet->setCellValue('H2', "公司主体");
        $k = 3;
        foreach($data as $x =>$v){
            $y = $x+1;
            foreach($v['detail'] as $c =>$i){
                if($c == 0){
                    $currentSheet->setCellValue('A'.$k,$y.'/'.$num);
                    $currentSheet->mergeCells('A'.$k.':A'.(count($v['detail'])+$k-1));
                }
                $currentSheet->setCellValue('B'.$k,$i['sku']);
                $currentSheet->setCellValue('C'.$k,'');
                $currentSheet->setCellValue('D'.$k,$i['quantity']);
                if($c == 0){
                    $currentSheet->setCellValue('E'.$k,$v['weight']);
                    $currentSheet->mergeCells('E'.$k.':E'.(count($v['detail'])+$k-1));
                    $currentSheet->setCellValue('F'.$k,$v['size']);
                    $currentSheet->mergeCells('F'.$k.':F'.(count($v['detail'])+$k-1));
                }
                $currentSheet->setCellValue('G'.$k,$i['export_tax_rebate']==1?'是':'否');
                $currentSheet->setCellValue('H'.$k,PublicInfoService::getCompanyName($i['enterprise_dominant']));
                $k +=1;
            }

        }
        $PHPWriter = new \PHPExcel_Writer_Excel2007($PHPExcel);
        ob_start();
        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header('Content-Disposition:attachment;filename="' .$outputFileName. '"');//输出模板名称
        header("Content-Transfer-Encoding: binary");
        header("Last-Modified:".gmdate("D, d M Y H:i:s")." GMT");
        header('Pragma: public');
        header('Expires: 30');
        header('Cache-Control: public');
        $PHPWriter->save('php://output');
    }
    /**
     * 下载装箱数据
     */
    public function download_box_ther(){
        set_time_limit(0);
        $id=I('get.id');
        $shipmentid=trim(I('get.shipmentid'));
        $load = $this->Inboundshipmentplan->select(array('shipmentid'=>$shipmentid),TRUE);
        $package_box_id = M('package_box','fba_','DB_FBAERP')->where("id in ($id)")->select();
        foreach($package_box_id as $k =>$v){
            $data[$k]['detail'] = M('package_box_details','fba_','DB_FBAERP')->where("package_box_id = ".$v['id'])->select();
//            print_r($data[$k]['detail']);
//            exit;
            foreach($data[$k]['detail'] as $a =>$c) {
                $data[$k]['detail'][$a]['enterprise_dominant'] = $this->Inboundshipmentplan->getEnterprise($data[$k]['detail'][$a]['inbound_shipment_plan_id'],$data[$k]['detail'][$a]['sku']);
                $data[$k]['detail'][$a]['export_tax_rebate'] = $v['export_tax_rebate'];
                $data[$k]['detail'][$a]['purchaseorders_id']=PublicInfoService::getPurchaseordersId($data[$k]['detail'][$a]['inbound_shipment_plan_id'],$data[$k]['detail'][$a]['sku']);
                $weight=PublicInfoService::getWeight($data[$k]['detail'][$a]['sku']);
                $totalWeight=$weight*$data[$k]['detail'][$a]['quantity'];
                $data[$k]['detail'][$a]['total_weight']=$totalWeight;
            }
            $data[$k]['weight'] = $v['weight'];
            $data[$k]['size'] = $v['length'].'*'.$v['width'].'*'.$v['height'];
            $data[$k]['shipmentid'] = $shipmentid;
        }
//        print_r($data);
//        exit;
        //$data = M('package_box_details','fba_','DB_FBAERP')->where("package_box_id = $id")->select();
        $num = count($data);
//        dump($data);die;
        vendor('PHPExcel.PHPExcel');
        /*模板存放目录*/
        $templateFile = realpath(__ROOT__) . '/Admin/Inbound/Template/' . date('Y-m-d',time());
        //$templateFile = '/var/www/fbawarehouse'. '/Admin/Inbound/Template/' . $templateFileName;

        /*目标投放文件名*/
        $outputFileName = 'FBA拼箱拼板单.xlsx';
        $PHPExcel = new \PHPExcel();
        //$PHPReader = new \PHPExcel_Reader_Excel2007();

        $currentSheet = $PHPExcel->getSheet(0);
        $PHPExcel->getDefaultStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
        $PHPExcel->getDefaultStyle()->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $currentSheet->getStyle('A1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $currentSheet->getColumnDimension('A')->setWidth(20);
        $currentSheet->getColumnDimension('B')->setWidth(20);
        $currentSheet->getColumnDimension('C')->setWidth(20);
        $currentSheet->getColumnDimension('D')->setWidth(20);
        $currentSheet->getColumnDimension('E')->setWidth(20);
        $currentSheet->getColumnDimension('F')->setWidth(20);
//        $currentSheet->mergeCells('A1:H1');
//        $currentSheet->setCellValue('A1','Package list');
        $currentSheet->setCellValue('A1','托盘号');
        $currentSheet->setCellValue('B1','托盘规格(CM)（打托后尺寸）');
        $currentSheet->setCellValue('C1', '总毛重（KG)含托盘，纸箱');
        $currentSheet->setCellValue('D1', "纸箱号");
        $currentSheet->setCellValue('E1', "纸箱规格（CM）（纸箱包装后后尺寸）");
        $currentSheet->setCellValue('F1', "整箱毛重（KG)");
        $currentSheet->setCellValue('G1', "整箱净重（KG）指的是货物净重");
        $currentSheet->setCellValue('H1', "ShipmentId");
        $currentSheet->setCellValue('I1', "SKU");
        $currentSheet->setCellValue('J1', "采购订单号");
        $currentSheet->setCellValue('K1', "采购名称");
        $currentSheet->setCellValue('L1', "报关品名");
        $currentSheet->setCellValue('M1', "Quantity(PCS)");
        $currentSheet->setCellValue('N1', "是否出口退税");
        $currentSheet->setCellValue('O1', "采购主体");
        $k = 2;
        foreach($data as $x =>$v){
            $y = $x+1;
            foreach($v['detail'] as $c =>$i){
                if($c == 0){
                    $currentSheet->setCellValue('A'.$k,'');
                    $currentSheet->mergeCells('A'.$k.':A'.(count($v['detail'])+$k-1));
                    $currentSheet->setCellValue('B'.$k,'');
                    $currentSheet->mergeCells('B'.$k.':B'.(count($v['detail'])+$k-1));
                    $currentSheet->setCellValue('C'.$k,'');
                    $currentSheet->mergeCells('C'.$k.':C'.(count($v['detail'])+$k-1));
                    $currentSheet->setCellValue('D'.$k,$y.'/'.$num);
                    $currentSheet->mergeCells('D'.$k.':D'.(count($v['detail'])+$k-1));
                    $currentSheet->setCellValue('E'.$k,$v['size']);
                    $currentSheet->mergeCells('E'.$k.':E'.(count($v['detail'])+$k-1));
                    $currentSheet->setCellValue('F'.$k,$v['weight']);
                    $currentSheet->mergeCells('F'.$k.':F'.(count($v['detail'])+$k-1));
                    $currentSheet->setCellValue('H'.$k,$v['shipmentid']);
                    $currentSheet->mergeCells('H'.$k.':H'.(count($v['detail'])+$k-1));
                }
                $currentSheet->setCellValue('G'.$k,$i['total_weight']);
                $currentSheet->setCellValue('I'.$k,$i['sku']);
                $currentSheet->setCellValue('J'.$k,$i['purchaseorders_id']);
                $currentSheet->setCellValue('K'.$k,$i['sku_name']);
                $currentSheet->setCellValue('L'.$k,$i['sku_cname']);
                $currentSheet->setCellValue('M'.$k,$i['quantity']);
                $currentSheet->setCellValue('N'.$k,$i['export_tax_rebate']==1?'是':'否');
                $currentSheet->setCellValue('O'.$k,PublicInfoService::getCompanyName($i['enterprise_dominant']));
                $k +=1;
            }
        }
        $PHPWriter = new \PHPExcel_Writer_Excel2007($PHPExcel);
        ob_start();
        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header('Content-Disposition:attachment;filename="' .$outputFileName. '"');//输出模板名称
        header("Content-Transfer-Encoding: binary");
        header("Last-Modified:".gmdate("D, d M Y H:i:s")." GMT");
        header('Pragma: public');
        header('Expires: 30');
        header('Cache-Control: public');
        $PHPWriter->save('php://output');
    }
    public function checkStatus(){
        $id = I('post.id');
        $status =  M('inbound_shipment_plan', 'fba_', 'DB_FBAERP')->where("id = $id")->field('status')->find();
        $arr = array('40', '50', '60');
        if(in_array($status['status'], $arr)){
            $this->ajaxReturn('101');
        }else{
            $this->ajaxReturn('404');
        }
    }

    /**
     * 描述: 显示sku的储位及库存
     * 作者: kelvin
     */
    public function showPickSku() {
        C("LAYOUT_ON", FALSE);
        C('SHOW_PAGE_TRACE', false);
        $id = I('get.id');
        $status = $this->Inboundshipmentplan->getStatus($id);
        if ($status['status'] != '15'){
            echo "<script>alert('该状态不能操作');parent.layer.closeAll();</script>";
            die;
        }
        $result = $this->Inboundshipmentplan->getSkuDetailByShipmentId($id);
        if (isset($result['status']) && $result['status'] != 200) {
            echo "<script>alert('".$result['msg']."');parent.layer.closeAll();</script>";
            die;
        }

        $this->assign('shipmentId', I('get.shipmentId'));
        $this->assign('site_id', PublicInfoService::get_site_id(trim(I('get.site_id'))));
        $this->assign('accountName', I('get.accountName'));
        $this->assign('seller_id', I('get.seller_id'));
        $this->assign('shipmentPlanId', $id);
        $this->assign('batch_code', I('get.batch_code'));
        $this->assign('skuDetail', $result);
        $this->display();
    }
    /**
     * 描述: 捡货单确认
     * 作者: kelvin
     */
    public function savePickSku() {
        $list = I('post.');
        if (empty($list) || !isset($list)) {
            return FALSE;
        }
        $dataList = array();
        $data = array();
        $data['shipmentid'] = $list['shipmentId'];
        $data['site_id'] = $list['site_id'];
        $data['seller_id'] = $list['seller_id'];
        $data['inbound_shipment_plan_id'] = $list['shipmentPlanId'];
        $data['accountName'] = $list['accountName'];
        foreach ($list['fnsku'] as $k => $sku) {
            $data['sku'] = $list['sku'][$k];
            $data['fnsku'] = $list['fnsku'][$k];
            $data['inbound_shipment_plan_details_id'] = $list[$sku]['detailId'];
            $data['export_tax_rebate'] = $list[$sku]['export_tax_rebate'];
            $data['pick_quantity'] = $list[$sku]['quantity'];
            $data['enterpriseDominantsName'] = PublicInfoService::getCompanyId(trim($list[$sku]['enterpriseDominantsName']));

            foreach($list[$sku]['position'] as $k =>&$v){
                if ($list[$sku]['advise_quantity'][$k] == 0){
                    continue;
                }
                $data['pick_storage'][$v] = $list[$sku]['advise_quantity'][$k];
            }
            $dataList[] = $data;
            unset($data['pick_storage']);
        }
        $res = $this->Inboundshipmentplan->savePickSku($dataList);
        if(!is_array($res)){
            echo "<script>alert('$res');parent.layer.closeAll();</script>";
            die;
        }
        if (in_array('400', $res)) {
            echo "<script>alert('操作失败');parent.layer.closeAll();</script>";
            die;
        } else {
            $inboundShipmentPlan =  M('inbound_shipment_plan', 'fba_', 'DB_FBAERP');
            $arr = array(
                'status'=>20,
                'picking_user_id'=>$_SESSION['current_account']['id'],
                'picking_time'=>date('Y-m-d H:i:s', time())
            );
            $inboundShipmentPlan->where("id = '".$data['inbound_shipment_plan_id']."'")->setField($arr);
            //推送平台计划单接口
            D('Api/Amazon/Client','Controller')->shipmentIdpost($data['shipmentid']);
            echo "<script>alert('操作成功');parent.location.reload();</script>";
            die;
        }
    }

    /**
     * 描述: shipmentid返仓申请
     * 作者: kelvin
     */
    public function shipmentIdBack() {
        if ($_GET) {
            if (!I('get.shipmentid')){
                echo "<script>alert('请输入shipmentid');history.go(-1);</script>";
            }
            $_GET['status'] = array(array('egt',20),array('elt',50));
            $arr = PublicInfoService::get_inbound_status();
            $data = $this->Inboundshipmentplan->select($_GET, TRUE);
            $status = array_search($data[0]['status'], $arr);
            $this->assign('back_type', PublicInfoService::getNameForBackStatus('back_type'));
            $this->assign('status', $status);
            $this->assign('data' ,$data);
        }
        $this->display();
    }

    /**
     * 描述: shipmentid返仓入库列表
     * 作者: kelvin
     */
     public function shipmentIdBackList() {
         $role_id = PublicInfoService::getIdFormNodeName('checkPosition');
         $role = PublicInfoService::getRoleIdFromNodeId($role_id);
         if (in_array($_SESSION['current_account']['role_id'],$role)) {
             $success = 1;
         } else {
             $success = 0;
         }
         $data = $this->Inboundshipmentplan->selectBackShipment($_GET);
         $this->assign('back_status', PublicInfoService::getNameForBackStatus('back_status'));
         $this->assign('sellers', PublicInfoService::salesmanGet());
         $this->assign('accounts', $this->accounts);
         $this->assign('success', $success);
         $this->assign('role_id', $_SESSION['current_account']['role_id']);
         $this->assign('data', $data);
         $this->assign('page',$this->Inboundshipmentplan->page);
         $this->assign('count',$this->Inboundshipmentplan->count);
         $this->display();
     }

     /**
      * 描述: 返仓申请确认
      * 作者: kelvin
      */
    public function backShipmentIdSave() {
        $boxModel = M('package_box_details','fba_','DB_FBAERP');
        $item             = M('inbound_shipment_plan_detail','fba_','DB_FBAERP');
        $data = I('post.');
        $planId  = $data['planId'];
//        $boxNum = $boxModel->where("inbound_shipment_plan_id = '".$planId."'")->count();
        $num = count($data['detailId']);
        $list = array();
        $details_id = array();
        $sku = array();
        $y = 0;
        $msg = '';
        for ($i=0; $i<$num; $i++) {
            if (!in_array($data['detailId'][$i], $data['planDetailId'])) {
                continue;
            }
            if ($this->Inboundshipmentplan->checkBackShipment($data['shipmentid'][$i], $data['sku'][$i])) {
                $msg .= $data['shipmentid'][$i].'的'.$data['sku'][$i].'已存在 \n';
            }
            $details_id[]=trim($data['detailId'][$i]);
            $sku[]=trim($data['sku'][$i]);
            $list[$y]['inbound_shipment_plan_details_id'] = trim($data['detailId'][$i]);
            $list[$y]['account_id'] = trim($data['account_id'][$i]);
            $list[$y]['deliveryorders_id'] = trim($data['deliveryorders_id'][$i]);
            $list[$y]['shipmentid'] = trim($data['shipmentid'][$i]);
            $list[$y]['seller_id'] = trim($data['seller_id'][$i]);
            $list[$y]['sku'] = trim($data['sku'][$i]);
            $list[$y]['back_quantity'] = trim($data['quantity'][$i]);
            $list[$y]['sku_name'] = trim($data['sku_name'][$i]);
            $list[$y]['export_tax_rebate'] = trim($data['export_tax_rebate'][$i])=='是'?1:0;
            $list[$y]['enterprise_dominant'] =  trim(PublicInfoService::getCompanyId(trim($data['enterprise_dominant'][$i])));
            $list[$y]['back_type'] = trim($data['back_type'][$i]);
            $list[$y]['reason'] = trim($data['reason'][$i]);
            $list[$y]['back_status'] = 10;
            $list[$y]['back_apply_user_id'] = $_SESSION['current_account']['id'];
            $list[$y]['back_apply_time'] = date('Y-m-d H:i:s', time());
            $y += 1;
        }
        if (!empty($msg)) {
            echo "<script>alert('".$msg."');history.go(-1)</script>";
            die;
        }
        if ($list) {
            $save = $this->Inboundshipmentplan->backShipmentIdSave($list);
            if ($save) {
                $where['id'] = array('in',$details_id);
                $re = $item->where($where)->setField('quantity',0);
                if($re){
                   $this->Inboundshipmentplan->updateStatusForDetailQuantity($planId);
                    //装箱数据存在则删除对应的装箱数据
//                    if ($boxNum > 0) {
//                        $box = array(
//                            'inbound_shipment_plan_id' => $planId,
//                            'sku' => array('in',$sku),
//                        );
//                        $box_id =  $boxModel->where($box)->getField('package_box_id',TRUE);
//                        $boxResult = $boxModel->where($box)->delete();
//                        if($box_id) {
//                            $package = array(
//                                'id' => array('in',$box_id),
//                            );
//                            $packageResult = $packageModel->where($package)->delete();
//                            if(!$packageResult) {
//                                $err .= '部分成功，删除箱唛数据失败</br>';
//                                //                            echo "<script>alert('部分成功，删除箱唛数据失败'); history.go(-1)</script>";die;
//                            }
//                        }
//                        if(!$boxResult){
//                            $err .= '部分成功，删除装箱sku数据失败</br>';
////                             echo "<script>alert('部分成功，删除装箱sku数据失败'); history.go(-1)</script>";die;
//                        }
//
//                        if($err!=''){
//                            echo "<script>alert('".$err."');history.go(-1)</script>";die;
//                        }
//
//                    }
                    echo "<script>alert('操作成功'); location.href='shipmentIdBack'</script>";
                }else{
                    echo "<script>alert('修改计划单sku数量失败'); history.go(-1)</script>";
                }

            } else {
                echo "<script>alert('操作失败'); history.go(-1)</script>";
            }
        }
    }
    /**
     * 描述: 返仓审核
     * 作者: kelvin
     */
    public function examineBackShipment() {
        $str = I('post.id');
        if ($str) {
            $data = array(
                'back_status' => 20,
                'confirm_user_id' => $_SESSION['current_account']['id'],
                'confirm_time' => date('Y-m-d H:i:s', time())
            );
            $str = implode(',', $str);
            $shipmentBackModel = M('shipment_back', 'fba_', 'DB_FBAERP');
            $result = $shipmentBackModel->where('id in ('.$str.')')->setField($data);
            if ($result) {
                $this->ajaxReturn(array('status'=>200,'msg'=>'操作成功'));
            } else {
                $this->ajaxReturn(array('status'=>400,'msg'=>'操作失败'));
            }
        } else {
            $this->ajaxReturn(array('status'=>500,'msg'=>'参数错误'));
        }
    }

    /**
     * 描述: 实物返仓
     * 作者: kelvin
     */
    public function saveBackShipment() {
        $num = count(I('post.position'));
        $_array = I('post.');
//        $msg = $this->checkPosition($_array['position']);
        $shipment_back_id = I('post.backId');
        $stockIn = new StockInController();
        $head = M('inbound_shipment_plan', 'fba_', 'DB_FBAERP');
//        $item = M('inbound_shipment_plan_detail', 'fba_', 'DB_FBAERP');
        $sel['id'] = $shipment_back_id;
        $result = $this->Inboundshipmentplan->selectBackShipment($sel);
//        $qtyNum = 0;
        //亚马逊平台修改计划单接口数据整理
        $shipmentId = $result[0]['shipmentid'];
        $apiHead = $head->where("shipmentid = '$shipmentId'")->
                field('id,shipmentid,account_id,shipment_name, destination_fullfillment_center_id')->find();
//        $apiItems = $item->where(" inbound_shipment_plan_id = ".$apiHead['id'])->field('sku, seller_sku, quantity')->select();
//        $apiItemsList = array();
//        foreach ($apiItems as $k =>$v) {
//            $apiItemsList[$k]['SellerSKU'] = $v['seller_sku'];
//            if ($v['sku'] == $result[0]['sku']) {
//                $apiItemsList[$k]['QuantityShipped'] = 0;
//            } else {
//                $apiItemsList[$k]['QuantityShipped'] = $v['quantity'];
//            }
//            $qtyNum += $apiItemsList[$k]['QuantityShipped'];
//        }
        $account = $apiHead['account_id'];
//        $options = array();
//        $options['ShipmentId'] = $shipmentId;
//        $options['InboundShipmentHeader']['ShipmentName'] = $apiHead['shipment_name'];
//        $options['InboundShipmentHeader']['DestinationFulfillmentCenterId'] = $apiHead['destination_fullfillment_center_id'];
//        $options['InboundShipmentHeader']['LabelPrepPreference'] = 'SELLER_LABEL';
//        $options['InboundShipmentHeader']['ShipmentStatus'] = 'WORKING';
//        $options['InboundShipmentItems'] = $apiItemsList;

        if ($result[0]['back_status'] != 20) {
            echo "<script>alert('该sku已经返仓');location.href='shipmentIdBackList'</script>";
            die;
        }
        $data = array();
        for ($i = 0; $i < $num; $i++) {
            $data[$i]['sku']  = $result[0]['sku'];
            $data[$i]['sku_name']  = $result[0]['sku_name'];
            $data[$i]['type']  = 80;
            $data[$i]['site_id']  = PublicInfoService::getSiteIdByAccountId($account);
            $data[$i]['storage_position']  = $_array['position'][$i];
            $data[$i]['warehouse_quantity'] = $_array['quantity'][$i];
            $data[$i]['deliveryorders_id']  = $result[0]['deliveryorders_id'];
        }
//        if ($qtyNum == 0) {
//            $api = $this->API_Inbound->delInboundShipment($account, $shipmentId);
//            if ($api==$shipmentId) {
//                $head->where("shipmentid = '$shipmentId'")->setField('status',100);
//            }
//        } else {
//            $api = $this->API_Inbound->updateInboundShipment($account, $options);
//        }
//        if ($api != $shipmentId) {
//            echo "<script>alert('API接口调用失败:".$api['msg']."');history.go(-1)</script>";
//        }

//        $where = array(
//            'inbound_shipment_plan_id' => $apiHead['id'],
//            'sku' => $result[0]['sku']
//        );
//        $item->where($where)->setField('quantity',0);
        $result = $stockIn->Back_StockIn($data);
        if (is_array($result) && count($result)!=0) {
            $arr = array();
            $warehouse_id_str = '';
            foreach ($result as $re) {
                $arr[] = array($re['storage_position'], $re['warehouse_quantity'], $re['id']);
                $warehouse_id_str .= $re['id'].',';
            }
            $storage_json = json_encode($arr);
            if ($arr && $storage_json) {
                $res = $this->Inboundshipmentplan->saveBackShipment($shipment_back_id, $storage_json, $warehouse_id_str);
                if ($res) {
                    echo "<script>alert('操作成功');location.href='shipmentIdBackList'</script>";
                } else {
                    echo "<script>alert('返仓列表更新失败');history.go(-1)</script>";
                }
            } else {
                echo "<script>alert('操作失败');history.go(-1)</script>";
            }
        } else {
            echo "<script>alert('入库更新失败');history.go(-1)</script>";
        }

    }

    /**
     * 描述: 检测储位是否可用
     * 作者: kelvin
     */
     public function checkPosition() {
       $storage = D('Warehouse/Storage','Service');
       $array = I('post.position');
       $result = $storage->validate_storage($array);
       $msg = '';
       foreach ($result as $k =>$v) {
           if ($v == 0) {
               $msg .= $k."储位不存在<br>";
           }
       }
       if ($msg == '') {
           $data = array(
               'status' => 200,
               'msg' =>''
           );
       } else {
           $data = array(
               'status' => 400,
               'msg' =>$msg
           );
       }
       $this->ajaxReturn($data);
     }
     /**
      * 描述: shipmentId不良申请
      * 作者: kelvin
      */
     public function shipmentIdRejects() {
         if ($_GET) {
             $_GET['status'] = 20;
//             $data = $this->Inboundshipmentplan->moveSelect($_GET);
             $data = $this->Inboundshipmentplan->select($_GET,TRUE);
             if ($data[0]['status'] == '待录入箱唛数据') {
                 $this->assign('data', $data);
             } else {
                 echo "<script>alert('只有待录入箱唛数据状态才能进行不良申请');history.go(-1);</script>";die;
             }
//             dump($data);die;
         }

         $role = $_SESSION['current_account']['role_id'];
         $this->assign('role', $role);
         $this->assign('accounts', $this->accounts);
         $this->display();
     }

     /**
      * 描述: shipmentId不良申请确认
      * 作者: kelvin
      */
     public function shipmentIdRejectsSave() {
         $arr = I('post.');
         $data = array();
         $num = count($arr['account_id']);
         $y = 0;
         for ($i=0; $i<$num; $i++) {
             if(empty($arr['quantity'][$i])) continue;
             $data[$y]['inbound_shipment_plan_details_id'] =  $arr['detail_id'][$i];
             $data[$y]['account_id'] =  $arr['account_id'][$i];
             $data[$y]['shipmentid'] =  $arr['shipmentid'];
             $data[$y]['site_id'] =  PublicInfoService::get_site_id($arr['site_id']);
             $data[$y]['seller_id'] =  $arr['seller_id'];
             $data[$y]['sku'] =  $arr['sku'][$i];
             $data[$y]['sku_name'] =  $arr['sku_name'][$i];
             $data[$y]['ori_qty'] =  $arr['old_quantity'][$i];
             $data[$y]['rej_qty'] =  $arr['quantity'][$i];
             $data[$y]['export_tax_rebate'] =  trim($arr['export_tax_rebate'][$i])=='是'?1:0;
             $data[$y]['enterprise_dominant'] =  trim(PublicInfoService::getCompanyId(trim($arr['enterprise_dominant'][$i])));
             $data[$y]['tranfer_hopper_id'] =  ' ';//中转仓id
             $data[$y]['remark'] =  $arr['remark'][$i];
             $data[$y]['rejects_apply_user_id'] =  $_SESSION['current_account']['id'];
             $data[$y]['rejects_apply_time'] =  date('Y-m-d H:i:s', time());
             $data[$y]['rejects_status'] =  10;
             $y+=1;

         }
         $move = M('shipment_rejects', 'fba_', 'DB_FBAERP');
         if ($move->addAll($data)) {
             echo "<script>alert('操作成功');window.location.href = 'shipmentIdRejects'</script>";
         } else {
             echo "<script>alert('操作失败');history.go(-1);</script>";
         }
     }
    /**
     * 描述: shipmentId不良申请列表
     * 作者: kelvin
     */
    public function shipmentIdRejectsList() {
        $data = array();
        if($_GET){
            $data = $this->Inboundshipmentplan->shipmentIdRejectsList($_GET);
        }
        $seller= PublicInfoService::getIdFormNodeName('rejectsSellerSave');
        $back = PublicInfoService::getIdFormNodeName('rejectsBackSave');
        $sellerSave = PublicInfoService::getRoleIdFromNodeId($seller);
        $backSave = PublicInfoService::getRoleIdFromNodeId($back);
        if (in_array($_SESSION['current_account']['role_id'],$sellerSave)) {
            $sellerSaveOk = 1;
        } else {
            $sellerSaveOk = 0;
        }
        if (in_array($_SESSION['current_account']['role_id'],$backSave)) {
            $backSaveOk = 1;
        } else {
            $backSaveOk = 0;
        }
        $role = $_SESSION['current_account']['role_id'];
        $this->assign('role', $role);
        $this->assign('accounts', $this->accounts);
        $this->assign('backSaveOk' ,$backSaveOk);
        $this->assign('sellerSaveOk' ,$sellerSaveOk);
        $this->assign('data' ,$data);
        $this->assign('status', PublicInfoService::getNameForStatus('fba_shipment_rejects','rejects_status'));
        $this->assign('type', PublicInfoService::getNameForStatus('fba_shipment_rejects','rejects_type'));
        $this->assign('page',$this->Inboundshipmentplan->page);
        $this->assign('count',$this->Inboundshipmentplan->count);
        $this->display();
    }

    /**
     * 描述: 返回待推送仓库状态
     * 作者: kelvin
     */
    public function returnStatus() {
        $id = I('post.id');
        if ($id) {
            $planModel = M('inbound_shipment_plan', 'fba_', 'DB_FBAERP');
            $re = $planModel->where("id = $id")->setField('status', 10);
            if ($re) {
                $msg = array(
                    'status'=>200,
                    'msg'=>'操作成功'
                );
            } else {
                $msg = array(
                    'status'=>400,
                    'msg'=>'操作失败'
                );
            }
        } else {
            $msg = array(
                'status'=>500,
                'msg'=>'操作失败,id为空'
            );
        }
        $this->ajaxReturn($msg);
    }

    /**
     * 描述: 不良处理销售选择
     * 作者: kelvin
     */
    public function rejectsSellerSave() {
        $id = I('post.id');
        $rejects_type = I('post.reject_type');
        $site_id = I('post.site_id');
        $data = $this->Inboundshipmentplan->rejectsSellerSave($id, $site_id, $rejects_type);
        $this->ajaxReturn($data);
    }

    /**
     * 描述: 良品返仓处理
     * 作者: kelvin
     */
    public function rejectsBackSave() {
        $post = I('post.');
        $data = $this->Inboundshipmentplan->rejectsBackSave($post);
        $this->ajaxReturn($data);
    }
    /**
     * 描述: 不良品返仓处理
     * 作者: kelvin
     */
    public function badProductsSave() {
        $post = I('post.');
        $data = $this->Inboundshipmentplan->badProductsSave($post);
        $this->ajaxReturn($data);
    }
    /**
     * 描述: 修改备注
     * 作者: kelvin
     */
    public function updateRemark() {
        $id = trim(I('post.id'));
        $remark = trim(I('post.remark'));
        $shipmentid = I('post.shipmentid');
        if ($id && $remark) {
            $planModel = M('inbound_shipment_plan', 'fba_', 'DB_FBAERP');
            $re = $planModel->where("id = $id")->setField('remark', $remark);
            if ($re) {
                $msg = array(
                    'status'=>200,
                    'msg' =>'操作成功'
                );
            }else{
                $msg = array(
                    'status'=>500,
                    'msg' =>'操作失败'
                );
            }
        }else if($shipmentid){
            $failureModel = M('shipment_shiped_failure', 'fba_', 'DB_FBAERP');
            $data = array(
                'seller_mark_shiped_status'=>20,
                'seller_shiped_user_id'=>$_SESSION['current_account']['id'],
                'seller_shiped_time'=>date('Y-m-d H:i:s')
            );
            $re = $failureModel->where("shipmentid = '$shipmentid'")->setField($data);
            if ($re) {
                $msg = array(
                    'status'=>200,
                    'msg'=>'操作成功'
                );
            } else {
                $msg = array(
                    'status'=>400,
                    'msg'=>'操作失败'
                );
            }
        } else {
            $msg = array(
                'status'=>500,
                'msg' =>'数据有误'
            );
        }

        $this->ajaxReturn($msg);
    }
    /**
     * 描述: 修改title
     * 作者: kelvin
     */
    public function updateTitle() {
        $detailId = trim(I('post.detailId'));
        $title = trim(I('post.title'));
        if ($detailId && $title) {
            $planModel = M('inbound_shipment_plan_detail', 'fba_', 'DB_FBAERP');
            $re = $planModel->where("id = $detailId")->setField('title', $title);
            if ($re) {
                $msg = array(
                    'status'=>200,
                    'msg' =>'操作成功'
                );
            }else{
                $msg = array(
                    'status'=>500,
                    'msg' =>'操作失败'
                );
            }
        }
        else {
            $msg = array(
                'status'=>500,
                'msg' =>'数据有误'
            );
        }

        $this->ajaxReturn($msg);
    }
    /**
     * 描述: 补单
     * 作者: kelvin
     */
    public function shipmentIdSingle() {
        $where = "";
        $data = array();
        if($_GET){
            if(!$_GET['sku']){
                echo "<script>alert('sku必填');history.go(-1);</script>";die;
            }
//            if($_GET['shipmentid']){
//                $where .= " AND `shipment`.`shipmentid` = '".$_GET['shipmentid']."'";
//            }
            if($_GET['sku']){
                $where .= " AND `w`.`sku` = '".trim($_GET['sku'])."'";
            }
            $sql = "SELECT 
              w.id,w.`warehouse_quantity` AS `fromWareQty`,su.name,w.sku,w.enterprise_dominant,w.export_tax_rebate,
              w.available_quantity
            FROM
              wms_warehouseorders AS w            
            LEFT JOIN
              wms_purchaseorder_details AS pd
            ON
              (
                pd.purchaseorder_id = w.purchaseorders_id AND pd.sku = w.sku
              )
            LEFT JOIN
              wms_purchaseorders AS pu
            ON
              pu.id = pd.purchaseorder_id
            LEFT JOIN
              skusystem_suppliers AS su
            ON
              su.id = w.supplier_id
            WHERE
            w.purchaseorders_id = 0 AND w.export_tax_rebate = 1 AND w.available_quantity > 0
              $where";
            $model = M('','','fbawarehouse');
            $result = $model->query($sql);
//            $status = PublicInfoService::get_inbound_status();
            $data = array();
            foreach($result as $k => $v) {

                $data[$v['seller_sku']]['sku']       = $v['sku'];
                $data[$v['seller_sku']]['sku_name']  = $v['sku_name'];
                $data[$v['seller_sku']]['quantity']  = $v['quantity'];
                $data[$v['seller_sku']]['purchaseOrder'][]  = array(
                    'warehouseorders_id'=>$v['id'],
                    'enterprise_dominant'=>$v['enterprise_dominant'],
                    'available_quantity'=>$v['available_quantity'],
                    'export_tax_rebate_name'=> $v['export_tax_rebate']==1?'退税':'非退税',
                    'export_tax_rebate'=> $v['export_tax_rebate'],
                    'enterprise_dominant_name'=>PublicInfoService::getCompanyName($v['enterprise_dominant']),
                    'fromWareQty'=>$v['fromWareQty'],
                    'exportSinglePrice'=>$v['exportSinglePrice'],
                    'name'=>$v['name'],
                    'puId'=>$v['puId'],
                );

            }
        }
        $this->assign('data',$data);
        $this->display();
    }
    /**
     * 描述: 保存采购单信息
     * 作者: kelvin
     */
    public function shipmentIdSingleSave() {
        $data = $_POST;
        $addData = array();
        foreach ($data as $k =>$v){
            foreach ($v as $n =>$c){
                $addData[] = array(
                    'sku'=>$k,
                    'warehouseorders_id'=>$c['warehouseorders_id'],
                    'enterprise_dominant'=>$c['enterprise_dominant'],
                    'export_tax_rebate'=>$c['export_tax_rebate'],
                    'ware_quantity'=>$c['fromWareQty'],
                    'export_single_price'=>$c['exportSinglePrice'],
                    'purchaseorder_id'=>$c['puId'],
                    'supplier_id'=>$c['supplier_id'],
                    'add_user_id '=>$_SESSION['current_account']['id'],
                    'add_time'=>date('Y-m-d H:i:s')
                );
            }

        }
        $sku = array_keys($data);
        $model = M('shipment_purchaseorder','fba_','fbawarehouse');
        $wareModel = M('warehouseorders','wms_','fbawarehouse');
        $msg = '';
        foreach ($addData as $a =>$d){
            $check = $this->Inboundshipmentplan->checkPuIdAndSku($d['warehouseorders_id'],$d['sku']);
            $str = " 采购单号".$d['purchaseorder_id']."为".$_SESSION['current_account']['remark']."后期录入，如与实际采购单入库数量不符或请款金额问题请找对应采购";
            $sql = "UPDATE `wms_warehouseorders` SET `remark` = IF(`remark` IS NULL,'$str', CONCAT(`remark`,'$str')),`purchaseorders_id` = ".$d['purchaseorder_id']." WHERE `id` = ".$d['warehouseorders_id'];
          if($check){
                if(!$model->where("id = ".$check['id'])->save($d) || !$wareModel->execute($sql)){
                    $msg = '更新出错';
                }
            }else{
                if(!$model->add($d) || !$wareModel->execute($sql)){
                    $msg = '插入出错';
                }
            }
        }
        if($msg == ''){
            echo "<script>alert('操作成功');window.location.href = 'shipmentIdSingle?sku=".$sku[0]."'</script>";
        }else{
            echo "<script>alert('".$msg."');history.go(-1);</script>";
        }
    }
    /**
     * 描述: AJAX检查采购单和sku是否存在
     * 作者: kelvin
     */
    public function checkPurchaseOrderId() {
        $model = M('shipment_purchaseorder_history','fba_','fbawarehouse');
        $model_hz = M('shipment_purchaseorder_history_hangzhou','fba_','fbawarehouse');
        if($_POST['purchaseorder_id'] && $_POST['sku']){
            if(trim($_POST['enterprise_dominant'])==2){
                $where1 = array(
                    'purchaseorder_id'=>$_POST['purchaseorder_id'],
                    'sku'=>$_POST['sku']
                );
                $data = $model_hz->where($where1)->find();
            }else{
                $where = array(
                    'purchaseorder_id'=>$_POST['purchaseorder_id'],
                    'sku'=>$_POST['sku'],
                    'enterprise_dominant'=>$_POST['enterprise_dominant']
                );
                $result = $model->where($where)->find();
                if($result){
                    $data = $result;
                }else{
                    $sql = "SELECT FORMAT(pd.money/pd.`quantity`,3) as 'export_single_price',pd.sku,pd.purchaseorder_id,
                        pd.supplier AS 'supplier_id'
                        FROM `wms_purchaseorder_details` AS pd 
                        left join wms_purchaseorders AS p on p.id = pd.`purchaseorder_id` 
                        WHERE pd.`purchaseorder_id` =  '".$_POST['purchaseorder_id']."'
                        AND pd.sku = '".$_POST['sku']."' 
                        AND p.enterprise_dominant = '".$_POST['enterprise_dominant']."'
                        AND p.status != 100 
                        AND pd.status != 100 
                        AND pd.status >= 65
                        LIMIT 1";
                    $re = M('','','fbawarehouse')->query($sql);
                    $data = $re?$re[0]:null;
                }
            }
            if($data){
                $msg = array(
                    'status' =>200,
                    'data' =>$data
                );
            }else{
                $msg = array(
                    'status' =>300,
                    'data' =>$_POST['sku'].'主体为'.PublicInfoService::getCompanyName($_POST['enterprise_dominant']).'的采购单号'.$_POST['purchaseorder_id'].'不存在'
                );
            }

        }else{
            $msg = array(
                'status' =>400,
                'data' =>'参数有误'
            );
        }
        $this->ajaxReturn($msg);
    }
    /**
     *  根据shipmentid下载装箱信息
     *  作者:kelvin
     * */
    public function upload_shipmentid()
    {
        $sheetData = PublicPlugService::parse_excel();                            //解析excel内容
        if(!$sheetData) {
            echo "<script>alert('文件内容解析有误，请检查文件内容');history.go(-1)</script>";
            exit;
        }
        if(!PublicPlugService::$flag){                                            //选择了上传文件,状态返回false
            if(count($sheetData)>=2){
                $result = '';
                $data = array();
                foreach ($sheetData as $c =>$v){
                    if($c>1){
                        if(trim($v['A'])==''){
                            $result .= '第'.$c.'行为空\\n';continue;
                        }
                        $data[] = $v['A'];
                    }
                }
                if($result!=''){
                    echo "<script>alert('".$result."');window.location.href = 'select_package_info'</script>";die;
                }else{
                    $this->Inboundshipmentplan->shipment_package_down(array_unique($data));
                }

            }else{
                echo "<script>alert('文件内容为空');history.go(-1)</script>";die;
            }
        }else{
            echo '<script>alert("请选择上传文件");history.go(-1)</script>';die;
        }
    }
}